"""
订单模型
定义订单、订单项相关的数据库模型
"""
from datetime import datetime
import enum
from app.extensions import db

class OrderStatus(enum.Enum):
    """订单状态枚举"""
    PENDING = 'pending'  # 待处理
    PROCESSING = 'processing'  # 处理中
    SHIPPED = 'shipped'  # 已发货
    DELIVERED = 'delivered'  # 已送达
    COMPLETED = 'completed'  # 已完成
    CANCELLED = 'cancelled'  # 已取消
    REFUNDED = 'refunded'  # 已退款

class PaymentStatus(enum.Enum):
    """支付状态枚举"""
    UNPAID = 'unpaid'  # 未支付
    PAID = 'paid'  # 已支付
    REFUNDED = 'refunded'  # 已退款
    PARTIALLY_REFUNDED = 'partially_refunded'  # 部分退款

class Order(db.Model):
    """订单模型"""
    __tablename__ = 'order'
    
    id = db.Column(db.Integer, primary_key=True)
    order_number = db.Column(db.String(50), unique=True, nullable=False, index=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, index=True)
    status = db.Column(db.String(20), nullable=False, default=OrderStatus.PENDING.value)
    total_amount = db.Column(db.Numeric(10, 2), nullable=False)
    shipping_address = db.Column(db.Text, nullable=False)
    shipping_method = db.Column(db.String(50), nullable=False)
    payment_method = db.Column(db.String(50), nullable=False)
    payment_status = db.Column(db.String(20), nullable=False, default=PaymentStatus.UNPAID.value)
    notes = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    items = db.relationship('OrderItem', backref='order', lazy='dynamic', cascade='all, delete-orphan')
    logistics = db.relationship('Logistics', backref='order', lazy='dynamic')
    
    def __repr__(self):
        return f'<Order {self.order_number}>'
    
    def to_dict(self, include_items=False):
        """转换为字典"""
        result = {
            'id': self.id,
            'order_number': self.order_number,
            'user_id': self.user_id,
            'status': self.status,
            'total_amount': float(self.total_amount),
            'shipping_address': self.shipping_address,
            'shipping_method': self.shipping_method,
            'payment_method': self.payment_method,
            'payment_status': self.payment_status,
            'notes': self.notes,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
        
        if include_items:
            result['items'] = [item.to_dict() for item in self.items]
            
        return result

class OrderItem(db.Model):
    """订单项模型"""
    __tablename__ = 'order_item'
    
    id = db.Column(db.Integer, primary_key=True)
    order_id = db.Column(db.Integer, db.ForeignKey('order.id'), nullable=False, index=True)
    product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)
    variant_id = db.Column(db.Integer, db.ForeignKey('product_variant.id'))
    quantity = db.Column(db.Integer, nullable=False, default=1)
    price = db.Column(db.Numeric(10, 2), nullable=False)
    subtotal = db.Column(db.Numeric(10, 2), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<OrderItem {self.id}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'order_id': self.order_id,
            'product_id': self.product_id,
            'variant_id': self.variant_id,
            'quantity': self.quantity,
            'price': float(self.price),
            'subtotal': float(self.subtotal),
            'created_at': self.created_at.isoformat() if self.created_at else None
        } 